# ==============================
# _*_ coding:utf-8 _*_
# _*_ by:zizle     _*_
# _*_ at:20230421  _*_
# ==============================

from fastapi import APIRouter, Query
from response import APIResponse
from db_utils import BaseDatabaseConnection
from utils.ths_api import THSApi


class RealTimeQuotation:
    def __init__(self):
        self.market_hot_file_prefix = 'mhot_'  # 市场热度实时数据文件名前缀
        self.indexes_file_prefix = 'indexes_'  # 指数实时行情数据文件名前缀

    # 主力合约实时行情，市场热度：资金流向，涨跌幅，日增仓
    def main_contract_real_time(self, indicator):
        ths_api = THSApi()
        codes = ths_api.get_main_codes()
        indicators = ['tradeDate', 'tradeTime', 'changeRatio', 'capitalFlow', 'dailyIncreasePosition']
        quotation = ths_api.get_main_market_hot(codes=[c['code'] for c in codes],
                                                indicators=indicators, file_prefix=self.market_hot_file_prefix)  # mhot: market hot
        keys = [indicator, 'name', 'code', 'tradeDate', 'tradeTime']
        res_quotation = []
        up, flat, down = (0, 0, 0)
        for q in quotation:
            oq = {k: v for k, v in q.items() if k in keys}
            if q[indicator] and q[indicator] > 0:
                up += 1
            elif q[indicator] and q[indicator] < 0:
                down += 1
            else:
                flat += 1
            res_quotation.append(oq)
        res_quotation.sort(key=lambda x: x[indicator] if x[indicator] else -999999999, reverse=True)
        total = len(res_quotation)
        res_hots = [
            {'key': 'up', 'count': up, 'percent': f'{round(up * 100 / total, 0)}%', 'bg': '#eb3323'},
            {'key': 'flat', 'count': flat, 'percent': f'{round(flat * 100 / total, 0)}%', 'bg': '#aaaaaa'},
            {'key': 'down', 'count': down, 'percent': f'{round(down * 100 / total, 0)}%', 'bg': '#44952a'},
        ]
        data = {
            'quotation': res_quotation,
            'hots': res_hots,
            'color': max(res_hots, key=lambda x: x['count'])['bg']
        }
        return APIResponse.success(data=data)

    # 指数的实时行情
    def indexes_real_time(self):
        # '000016.SH', '000300.SH', '000852.SH', '000905.SH',
        # '上证50', '沪深300', '中证1000', '中证500',
        indexes_list = [
            {
                'code': '000001.SH',
                'name': '上证指数',
                'index_type': '股指'
            },
            {
                'code': '399001.SZ',
                'name': '深证成指',
                'index_type': '股指'
            },
            {
                'code': 'IFZL.CFE',
                'name': '沪深300',
                'index_type': '期货'
            },
            {
                'code': 'IHZL.CFE',
                'name': '上证50',
                'index_type': '期货'
            },
            {
                'code': 'ICZL.CFE',
                'name': '中证500',
                'index_type': '期货'
            },
            {
                'code': 'IMZL.CFE',
                'name': '中证1000',
                'index_type': '期货'
            },
        ]
        codes = [c['code'] for c in indexes_list]
        indicators = ['tradeDate', 'tradeTime', 'open', 'low', 'high', 'latest', 'avgPrice', 'change', 'changeRatio']
        ths_api = THSApi()
        quotation = ths_api.get_index_real_quote(codes=codes, indicators=indicators,
                                                 file_prefix=self.indexes_file_prefix)
        quotes = {q['code']: q for q in quotation}
        # 处理数据返回前端
        for idx in indexes_list:
            _obj = quotes.get(idx['code'])
            idx['trade_date'] = '-'
            idx['cur_price'] = '-'
            idx['change_ratio'] = '-'
            idx['change'] = '-'
            idx['class_name'] = ''
            if _obj and _obj['tradeDate']:
                idx['trade_date'] = _obj['tradeDate']
            if _obj and _obj['open']:
                idx['open'] = _obj['open']
            if _obj and _obj['low']:
                idx['low'] = _obj['low']
            if _obj and _obj['high']:
                idx['high'] = _obj['high']
            if _obj and _obj['latest']:
                idx['cur_price'] = _obj['latest']
            if _obj and _obj['changeRatio']:
                idx['change_ratio'] = '{}%'.format(round(_obj['changeRatio'], 2))
            if _obj and _obj['change']:
                idx['change'] = round(_obj['change'], 2)
                idx['class_name'] = 'red' if _obj['change'] > 0 else 'green'

        res_data = {
            'quotation': indexes_list
        }
        return APIResponse.success(data=res_data)

    # 期货品种实时行情
    def variety_real_time(self, variety):
        ths_api = THSApi()
        quotation = ths_api.get_future_variety_real_quotation(variety=variety)
        quote = {
            'code': variety,
            'quote_time': '-',
            'price': '-',
            'change': '-',
            'change_ratio': '-'
        }
        if quotation:
            quote['quote_time'] = quotation['tradeDate'] + ' ' + quotation['tradeTime'][:5]
            quote['price'] = quotation['latest']
            quote['change'] = round(quotation['change'], 3)
            quote['change_ratio'] = round(quotation['changeRatio'], 3)
        res_data = {
            'data': quote
        }
        return APIResponse.success(data=res_data)


real_time_api = APIRouter()


# 主力实时行情
@real_time_api.get('/mainContract/')
def main_real_time_quotation(indicator: str = Query(...)):
    return RealTimeQuotation().main_contract_real_time(indicator)


# 指数和估值的实时行情
@real_time_api.get('/indexes/')
def indexes_real_time_quotation():
    return RealTimeQuotation().indexes_real_time()


# 指定期货品种实时行情
@real_time_api.get('/variety/')
def variety_real_time_quotation(variety: str = Query(...)):
    return RealTimeQuotation().variety_real_time(variety)
